/*zhaoyihang
 * 创建子进程
 * */
#include "threadPool.h"
void *threadFunc(void *arg){
    threadPool_t * threadPool = (threadPool_t *)arg;
    int netfd;
    while(1){
        // 准备取出任务
        pthread_mutex_lock(&threadPool->taskQueue.mutex);
        while(threadPool->exitFlag == 0 && threadPool->taskQueue.queueSize == 0){
            // 队列为空，子线程陷入等待
            printf("子线程准备接收工作！\n");
            pthread_cond_wait(&threadPool->taskQueue.cond, &threadPool->taskQueue.mutex);
        }
        if(threadPool->exitFlag != 0){
            printf("child thread is going to exit!\n");
            pthread_mutex_unlock(&threadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        printf("worker thread get task!\n");
        netfd = threadPool->taskQueue.pFront->netfd; // get queue top
        taskDeQueue(&threadPool->taskQueue);
        pthread_mutex_unlock(&threadPool->taskQueue.mutex);
        
        //接收登录标志
        int loging_flag;
        recv(netfd,&loging_flag,sizeof(int),0);

        if(loging_flag == 1)
        {
            char username[4096];            
            checkUser(netfd,username);
        }
        else if (loging_flag == 2)
        {
            Register(netfd,mysql);
        }
        //接收命令标志和内容
        int order_flag;
        char order_str[1024];
        int ret = recvOrder(netfd,&order_flag,order_str);
        switch(order_flag)
        {
        case 0:
            //考虑每次执行cd命令前通过pwd获取当前完整目录，
            //以便后面unit函数操作。
            printf("执行cd命令\n");
            break;
        case 1:
            printf("执行ls命令\n");
            ls_m(db,current_path,netfd);
            break;
        case 2:
            printf("子线程开始接收客户端文件\n");
            do_puts(order_str,netfd); 
            printf("服务端接收文件完毕！\n");
            break;
        case 3:
            printf("子进程开始给客户端发送文件\n");
            transFile(netfd,order_str);          
            printf("服务端将文件传输给了客户端");
            break;
        case 4:
            printf("执行remove命令\n");
            remove_m(db,current_path,netfd);
            break;
        case 5:
            printf("执行pwd命令\n");
            break;
        case 6:
            printf("执行mkdir命令\n");
            break;
        case 7:
            printf("执行rmdir命令\n");
        default:
            printf("你的命令错误\n");
            break;
        }
        sleep(5);
        //如何关何时关？
       // close(netfd);
    }
    close(netfd);
}

